package com.un.ebs.businessObject.service.impl;

import static java.util.stream.Collectors.toList;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import cn.hutool.core.util.StrUtil;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.sys.service.impl.TableWapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.un.ebs.core.enums.TableTypeEnum;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.metadata.FunctionInfo;
import com.un.ebs.core.metadata.ServiceExt;
import com.un.ebs.core.metadata.ServiceInfo;
import com.un.ebs.sys.domain.Table;
import com.un.ebs.sys.mapper.TableMapper;
import com.un.ebs.businessObject.service.RelAddService;
import com.un.ebs.businessObject.service.RelDeleteService;
import com.un.ebs.businessObject.service.RelGetByIdService;
import com.un.ebs.businessObject.service.RelListService;
import com.un.ebs.businessObject.service.RelPageListService;
import com.un.ebs.businessObject.service.RelQueryService;
import com.un.ebs.businessObject.service.RelService;
import com.un.ebs.businessObject.service.RelUpdateService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author zc
 * @ClassName RelServiceImpl
 * @Description 表字段关系service实现类
 * @Date 2021/1/8
 */
@Service
@Slf4j
public class RelServiceImpl implements RelService, ServiceExt {

    // 定义公共方法根路径
    private final String BASE_REQUEST_URL = "/common";

    @Autowired
    private TableMapper tableMapper;

    @Autowired
    private RelListService relListService;

    @Autowired
    private RelPageListService relPageListService;

    @Autowired
    private RelGetByIdService relGetByIdService;

    @Resource(name = "RelAddExtServiceImpl")
    private RelAddService relAddService;

    @Resource(name = "RelUpdateExtServiceImpl")
    private RelUpdateService relUpdateService;

    @Autowired
    private RelDeleteService relDeleteService;

    @Autowired
    private RelQueryService relQueryService;

    @Override
    public List<ServiceInfo> queryServices() {
        List<Table> list = queryTable();
        // 转换为List<ServiceInfo>
        System.out.println("......");
        System.out.println("标准服务加载 ------->>> " + this.getClass().getName());
        System.out.println("......");
        List<ServiceInfo> collect = list.stream().filter(s-> !StringUtils.isNullOrEmpty(s.getServiceName())).map(x -> converServiceInfo(x)).collect(toList());
        return collect;
    }

    public List<Table> queryTable() {
        LambdaQueryWrapper<Table> qw = new LambdaQueryWrapper<Table>();
        qw.eq(Table::getTableType, TableTypeEnum.BusinessObject);
        List<Table> list = tableMapper.selectList(qw);
        return list;
    }

    private ServiceInfo converServiceInfo(Table t) {
        ServiceInfo serviceInfo = new ServiceInfo();
        serviceInfo.setUrl(String.format("%s/%s", BASE_REQUEST_URL, t.getTableName()));
        serviceInfo.setName(t.getId());
        if (StrUtil.isNotBlank(t.getServiceName())) {
            serviceInfo.setDescription(t.getServiceName());
        } else if (StrUtil.isNotBlank(t.getTableName())) {
            serviceInfo.setDescription(t.getTableName());
        } else if (StrUtil.isNotBlank(t.getTableDesc())) {
            serviceInfo.setDescription(t.getTableDesc());
        }
        serviceInfo.setIsDynamic(true);
        return serviceInfo;
    }
	@Override
	public List<FunctionInfo> queryFunctions(String serviceName) {
		List<Table> tables = queryTable();
		Optional<Table> svc = tables.stream().filter(s -> s.getId().equals(serviceName)).findFirst();
		// 查询跟svc有关的所有table、分析它们之间的关系
		if (!svc.isPresent()) {
			throw new BusinessException("指定的服务 【 " + serviceName + " 】 没有找到。");
		}
        List<FunctionInfo> list = new ArrayList<>();

		Table table = svc.get();
		switch (table.getTableType()){
            case BusinessObject:
            case BusinessObjectSet:
                // add
                list.add(relAddService.getAddFunc(table));
                // update
                list.add(relUpdateService.getUpdateFunc(table));
                // delete
                list.add(relDeleteService.getDeleteFunc(table));
                break;
        }

		// query
		list.add(relListService.getListFunc(table));
		// queryPage
		list.add(relPageListService.getPageListFunc(table));
		// queryById
		list.add(relGetByIdService.getByIdFunc(table));
		// queryViewById
		list.add(relGetByIdService.getViewByIdFunc(table));

		// query
        list.add(relQueryService.getQueryFunc(table));
		
        return list;
    }

    @Override
    public List<Table> getDbTables(Table table) {
        List<Table> dbTables = new ArrayList<>();
        LambdaQueryWrapper<Table> qw = new LambdaQueryWrapper<Table>();
        qw.select(Table::getId, Table::getTableName, Table::getParentId);
        dbTables = tableMapper.selectList(qw);

//		// 订单详情
//		Table orderDetail = new TableWapper(); // 子类创建父类
//		orderDetail.setId("00B2C749-49DB-43B5-A5A7-51F1D4179D46");
//		orderDetail.setParentId(table.getId());
//		orderDetail.setTableName("tb_activity");
//		dbTables.add(orderDetail);

        // 订单详情-2
//		Table orderDetail2 = new TableWapper(); // 子类创建父类
//		orderDetail2.setId("1AF5F21F-3AA9-47DC-A9D3-331EDD6F6A74");
//		orderDetail2.setParentId(table.getId());
//		orderDetail2.setTableName("tb_product");
//		dbTables.add(orderDetail2);

//		// 订单票券
//		Table orderDetailItem = new TableWapper();
//		orderDetailItem.setId("034E2C0B-261C-4036-A2AF-A6F1F752C963");
//		orderDetailItem.setParentId("00B2C749-49DB-43B5-A5A7-51F1D4179D46");
//		orderDetailItem.setTableName("bz_order");
//		dbTables.add(orderDetailItem);
//		
//		// 订单票券-分部1
//		Table orderDetailItem_1 = new TableWapper();
//		orderDetailItem_1.setId("048F123C-6762-4F6B-8F28-DDEB6E3A67B9");
//		orderDetailItem_1.setParentId("034E2C0B-261C-4036-A2AF-A6F1F752C963");
//		orderDetailItem_1.setTableName("tb_product_class_attr");
//		dbTables.add(orderDetailItem_1);

        return dbTables;
    }

//    @Override
//    public Column getColumn(String refTable, String tableName) {
//        Column refColumn = new Column();
//        refColumn.setIsPk(Boolean.FALSE);
//        refColumn.setRefType(ColumnRefTypeEnum.FK);
//        refColumn.setRefTableName(refTable);
//        refColumn.setTableName(tableName);
//
//        // 第一级
//        if (tableName.equals("tb_activity")) {
//            refColumn.setRefColumnName("tb_order_id");
//        }
//        if (tableName.equals("tb_product")) {
//            refColumn.setRefColumnName("tb_order_id");
//        }
//
//        // 第二级
//        if (tableName.equals("bz_order")) {
//            refColumn.setRefColumnName("tb_activity_id");
//        }
//
//        // 第三级
//        if (tableName.equals("tb_product_class_attr")) {
//            refColumn.setRefColumnName("bz_order_id");
//        }

//        return refColumn;
//    }

    @Override
    public void recursiveTable(TableWapper tableWapper, List<Table> lists, String pid) {
        for (Table tb : lists) {
            if (pid.equals(tb.getParentId())) {
                // TableWapper child = (TableWapper) tb; // 父类不能直接强转成子类，除非父类是由该子类创建而来的！
                TableWapper childTb = new TableWapper(); // 子类转父类
                childTb.setId(tb.getId());
                childTb.setParentId(tb.getParentId());
                childTb.setTableName(tb.getTableName());
//				try {
//					BeanUtils.copyProperties(childTb, tb);
//				} catch (IllegalAccessException | InvocationTargetException e) {
//					log.error("getAddFunc转化table异常 error={}", e.getMessage());
//					e.printStackTrace();
//			}

                List<TableWapper> childs = tableWapper.getChilds();
                if (childs == null) {
                    childs = new ArrayList<>();
                }
                childs.add(childTb);
                tableWapper.setChilds(childs);

                recursiveTable(childTb, lists, tb.getId());
            }
        }

    }

    @Override
    public Table getTableById(String tabelId) {
        List<Table> tables = queryTable();
        Optional<Table> svc = tables.stream().filter(s -> s.getId().equals(tabelId)).findFirst();
        // 查询跟svc有关的所有table、分析它们之间的关系
        if (!svc.isPresent()) {
            throw new BusinessException("指定的服务 【 " + tabelId + " 】 没有找到。");
        }
        Table table = svc.get();
        return table;
    }
}
